﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using EntityManage;
using BusinessFacade;

public partial class Modules_Personal_PerfNotice : System.Web.UI.Page
{
    IPerf_Personal_ApprovalHandler approvalHandler = new Perf_Personal_ApprovalManage();
    ISys_UserHandler userHandler = new Sys_UserManage();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();
    ISys_OrganizationHandlerExt orgExtHandler = new Sys_OrganizationManageExt();
    ISys_PostHandler postHandler = new Sys_PostManage();
    IPerf_Personal_EvaluateHandler evaHandler = new Perf_Personal_EvaluateManage();
    IPerf_Personal_EvaluateDtlHandler evaDtlHandler = new Perf_Personal_EvaluateDtlManage();
    IPerf_Personal_TargetHandler targetHandler = new Perf_Personal_TargetManage();

    ISys_ConfigHandler configHandler = new Sys_ConfigManage();

    double baseScore = 100;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "ID";
            ViewState["Accending"] = "desc";

            dataBind(" 1=1 ", null);

        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("303040"))
            {

            }
            else
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    #region DataBind

    /// <summary>
    /// 初始化岗位信息表
    /// </summary>
    private void dataBind(string whereClause, SqlParameter[] parms)
    {
        try
        {
            int counter = 0;
            DataTable dt = new DataTable();

            // 读取本单位
            int userId = int.Parse(Session["CurrentUserID"].ToString());
            Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(userId);
            string orgIds = orgExtHandler.GetAllChildIdsByParentID(userQuery.Org_ID);

            int orgId = userQuery.Org_ID;
        
            //如果是所长室的用户 就把同级部门的人查出来
            string sameLevlOrgIDs = string.Empty;

            Sys_OrganizationQuery orgQuery = orgHandler.GetSys_OrganizationQuery(orgId);
            if (orgQuery != null)
            {
                if (orgQuery.Name == "所长室")
                {
                    Sys_OrganizationQuery[] orgQuerys = orgHandler.GetSys_OrganizationQueryList("Parent_ID=@Parent_ID and Status=1", new SqlParameter[] { new SqlParameter("@Parent_ID", orgQuery.Parent_ID) });
                    if (orgQuerys != null && orgQuerys.Length > 0)
                    {
                        foreach (Sys_OrganizationQuery q in orgQuerys)
                        {
                            sameLevlOrgIDs += q.ID + ",";
                        }
                    }
                }
            }


            orgIds = (orgIds.Length > 0 ? orgIds + "," + userQuery.Org_ID.ToString() : userQuery.Org_ID.ToString());

            if (sameLevlOrgIDs.TrimEnd(new char[] { ',' }).Length > 0)
            {
                orgIds = orgIds + "," + sameLevlOrgIDs.TrimEnd(new char[] { ',' });
            }

            Sys_UserQuery[] userList = userHandler.GetSys_UserQueryList(" (Org_ID in (" + orgIds + ") or Org_ID2 in (" + orgIds + ")) and Status = @Status"
            , new SqlParameter[] { new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid) });
            List<string> orgIdList = new List<string>();
            orgIdList.AddRange(orgIds.Split(','));
            StringBuilder userIds = new StringBuilder();
            if (userList != null && userList.Length > 0)
            {
                foreach (Sys_UserQuery user in userList)
                {
                    int userOrgId = (user.Org_ID2 != 0 ? user.Org_ID2 : user.Org_ID);

                    if (orgIdList.Contains(userOrgId.ToString()))
                    {
                        userIds.Append(user.ID);
                        userIds.Append(",");
                    }
                }
                userIds = userIds.Remove(userIds.Length - 1, 1);
            }

            whereClause += " and Target_User_ID in(" + userIds.ToString() + ")";

            dt = approvalHandler.GetPerf_Personal_ApprovalByPageList(whereClause, parms, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);

            counter = approvalHandler.GetCounter(whereClause, parms);

            this.AspNetPager.RecordCount = counter;
            gvPerfApproveList.DataSource = dt;
            gvPerfApproveList.DataBind();
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();

        if (ViewState["SearchPerfDate"] != null)
        {
            whereClause += " and Perf_Date = @Perf_Date";
            lstParm.Add(new SqlParameter("@Perf_Date", ViewState["SearchPerfDate"].ToString()));
        }

        parms = lstParm.ToArray();
    }

    #endregion

    #region gvPerfApproveList

    protected void gvPerfApproveList_RowCommand(object sender, GridViewCommandEventArgs e)
    {

    }

    protected void gvPerfApproveList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Sys_ConfigQuery ConfigQuery = configHandler.GetSys_ConfigQuery(1);
            if (ConfigQuery != null)
            {
                double.TryParse(ConfigQuery.ConfigValue, out baseScore);
            }

            HtmlInputCheckBox chkSelected = (HtmlInputCheckBox)e.Row.FindControl("chkSelected");
            if (int.Parse(e.Row.Cells[8].Text.Trim()) == (int)Enums.PersonalApprovalStatus.Passed)
                chkSelected.Visible = true;
            else
                chkSelected.Visible = false;

            if (e.Row.RowIndex > -1)
            {
                Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(int.Parse(e.Row.Cells[4].Text));
                if (userQuery != null)
                {
                    e.Row.Cells[4].Text = userQuery.Name;

                    Sys_OrganizationQuery orgQuery = orgHandler.GetSys_OrganizationQuery(userQuery.Org_ID);
                    if (orgQuery != null)
                        e.Row.Cells[2].Text = orgQuery.Name;
                    else
                        e.Row.Cells[2].Text = "";

                    Sys_PostQuery postQuery = postHandler.GetSys_PostQuery(userQuery.Post_ID);
                    if (postQuery != null)
                        e.Row.Cells[3].Text = postQuery.Name;
                    else
                        e.Row.Cells[3].Text = "";

                }

                int id = int.Parse(e.Row.Cells[7].Text);
                e.Row.Cells[7].Text = "";

                Perf_Personal_ApprovalQuery appQuery = approvalHandler.GetPerf_Personal_ApprovalQuery(id);
                if (appQuery != null)
                {
                    int evID = 0;
                    int.TryParse(appQuery.EvaluateIDs, out evID);
                    Perf_Personal_EvaluateQuery query = evaHandler.GetPerf_Personal_EvaluateQuery(evID);
                    if (query != null)
                    {
                        double totalScore = 0;
                        Perf_Personal_EvaluateDtlQuery[] dtlQueryList = evaDtlHandler.GetPerf_Personal_EvaluateDtlQueryList("Evaluate_ID = @Evaluate_ID", new SqlParameter[] { new SqlParameter("@Evaluate_ID", query.ID) });
                        if (dtlQueryList != null && dtlQueryList.Length > 0)
                        {
                            foreach (Perf_Personal_EvaluateDtlQuery dtlQuery in dtlQueryList)
                            {
                                Perf_Personal_TargetQuery targetQuery = targetHandler.GetPerf_Personal_TargetQuery(dtlQuery.Target_ID);
                                if (targetQuery != null)
                                    totalScore = totalScore + (dtlQuery.Score);
                            }
                        }
                        e.Row.Cells[7].Text = (baseScore + totalScore + appQuery.Plus_Score +appQuery.Task_Score).ToString();
                    }
                }

                // 状态
                Enums.PersonalApprovalStatus status = (Enums.PersonalApprovalStatus)int.Parse(e.Row.Cells[8].Text);
                e.Row.Cells[8].Text = Enums.GetPersonalApprovalStatus(status);
            }
        }
    }

    protected void gvPerfApproveList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        RefreshDataGridView();
    }

    #endregion

    #region Button


    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtPerfDate.Text != null && !"".Equals(txtPerfDate.Text))
            ViewState["SearchPerfDate"] = txtPerfDate.Text;
        else
            ViewState["SearchPerfDate"] = null;

        RefreshDataGridView();
    }

    protected void ApproveButton_Click(object sender, EventArgs e)
    {
        RefreshDataGridView();
    }

    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {
        RefreshDataGridView();
    }

    #endregion

    private void RefreshDataGridView()
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }

}
